﻿using System;
using System.Collections.Generic;
using SCG.SolarVengeanceEngine;
using SCG.SolarVengeanceEngine.StarShips;
using SCG.General;

namespace SCG.SolarVengeance.Scenarios
{
    public class SpacePortWars : Scenario
    {
        private SCGColor _ZonePen = new SCGColor(200, 128, 128, 128);
        private SCGColor _ZoneConflict = new SCGColor(64, 255, 0, 0);
        private SCGColor _ZoneTaking = new SCGColor(64, 255, 255, 0);
        private SCGColor _ZoneBar = new SCGColor(128, 0, 128, 0);

        private Dictionary<UDO, SCGRect> _zoneRects = new Dictionary<UDO, SCGRect>();
        private Dictionary<UDO, SCGRect> _zoneGuages = new Dictionary<UDO, SCGRect>();

        private int countdown = 60;
        private int CCcount = 200;
        private int totalplayers = 2;
        private int nzones = 0;
        private int BstValue = 20;
        private string laststarowner = "";
        private List<Player> ZoneOwner = new List<Player>();
        private List<int> ZoneStatus = new List<int>();
        private List<int> ZoneOwners = new List<int>();
        private Dictionary<Player, int> ZonesOwned = new Dictionary<Player, int>();
        private Dictionary<string, int> ShipsOwned = new Dictionary<string, int>();
        private List<bool> ZoneConflict = new List<bool>();
        private List<bool> ZoneTaking = new List<bool>();
        private ScenarioParameter pmNZones;
        private ScenarioParameter pmNebula;
        private ScenarioParameter pmWormHoles;
        private ScenarioParameter pmPulsars;
        private ScenarioParameter pmBlackHoles;
        private ScenarioParameter pmMode;
        private bool sceninit = true;
        //private int TeamZones;

        public SpacePortWars()           
        { pmNZones = CreateParameter("Unowned SpacePorts", 3, 1, 10);
          pmMode = CreateParameter("Game Mode", 1, 1, 3);
          pmNebula = CreateParameter("Nebula?", 1, 0, 1);
          pmWormHoles = CreateParameter("WormHoles?", 1, 0, 1);
          pmBlackHoles = CreateParameter("BlackHoles?", 1, 0, 1);
          pmPulsars = CreateParameter("Pulsars?", 1, 0, 1);
        }

        //Scenario description
        public override string Description
        {
            get
            {
                return "Can you take over all of the space ports before your opponent does? You start out with a star fleet and your mission is to occupy " +
                       " and defend all of the space ports. You can also win this mission by eliminating all of your opponent fleets. " + Environment.NewLine + Environment.NewLine +
                       "Each Player starts out with a cloaked BattleStaton with the preloaded starting resources, an uncloaked scanship, and one SpacePort. " +
                       "The SpacePort's self-positioning abilities allows it to be unaffected by a black holes's gavitational pull, but makes them an easy target for StarFleets." + Environment.NewLine + Environment.NewLine +
                       "NEW! This scenario is now alliance compatiable!" + Environment.NewLine + Environment.NewLine +
                       "Game Modes:" + Environment.NewLine +
                       "1: Normal Game." + Environment.NewLine +
                       "2: Survival Game. Each player is allowed to build from only ONE BattleStation." + Environment.NewLine +
                       "3: Triple Trouble. You got another way to win or lose by holding Central Control for 200 impulses" + Environment.NewLine; //+
                       //"4: Not yet assigned." + Environment.NewLine + "";
            }
        }
        public override bool CapitalElimination
        { get { return false; }
        }
        public override bool AssignCapitals
        { get { return false; }
        }
        public override PlayModeRecommendation Recommendation
        { get { return PlayModeRecommendation.MultiPlayer; }
        }
        public override string Author
        { get { return "Beat2k"; }
        }
        public override IList<StarShipType> DisallowStarShipTypes
        {
            get
            {   List<StarShipType> Disallowed = new List<StarShipType>();
                if ((pmMode.Value == 2) | (pmMode.Value == 4)) Disallowed.Add(StarShipType.BattleStation);
                return Disallowed; }
        }

        public override void ClientInitialize()
        {
            sceninit = true;
            countdown = 60;
            CCcount = 200;
            ZoneOwner.Clear();
            ZoneOwners.Clear();
            ZoneStatus.Clear();
            ZonesOwned.Clear();
            ZoneTaking.Clear();
            ShipsOwned.Clear();
        }

        //Declare alliance winners
        private void DeclareCountdownWinners(string PlayerName)
        {
            List<Player> GamePlayers = new List<Player>();
            Player basep = null;
            foreach (Player ply in Game.Players)
            {
                if (PlayerName == ply.Name) basep = ply;
            }
            if (basep != null)
            {
                GamePlayers.Add(basep);
                foreach (Player ply in Game.Players)
                {
                    if ((ply.AlliedWith(basep) == AllianceLevel.Formal) & 
                        (basep.AlliedWith(ply) == AllianceLevel.Formal) & (ply.Name != basep.Name))
                        GamePlayers.Add(ply);
                }
            }
            if (GamePlayers.Count > 0)
            {
                for (int d = 0; d < GamePlayers.Count; d++)
                {
                    GamePlayers[d].Victor = true;
                }
            }
        }
        private void StarShipAllianceWinCheck(Player basep)
        {
            List<Player> GamePlayers = new List<Player>();
            int StarShipsOwned = 0;
            if (basep != null)
            {
                GamePlayers.Add(basep);
                foreach (Player ply in Game.Players)
                {
                    if ((ply.AlliedWith(basep) == AllianceLevel.Formal) & 
                        (basep.AlliedWith(ply) == AllianceLevel.Formal) & (ply.Name != basep.Name))
                        GamePlayers.Add(ply);
                }
            }
            if (GamePlayers.Count > 0)
            {
                for (int d = 0; d < GamePlayers.Count; d++)
                {
                    foreach (StarShip ship in Game.StarShips)
                    {
                        if (ship.Owner.Name == GamePlayers[d].Name)
                            StarShipsOwned++;
                    }
                }
                if (StarShipsOwned >= Game.StarShips.Count)
                {
                    for (int d = 0; d < GamePlayers.Count; d++)
                    {
                        GamePlayers[d].Victor = true;
                    }
                }
            }
        }

        //Build the scenario
        public override void BuildScenario(int numPlayers, int capitalValues, int startingResources)
        {
            totalplayers = numPlayers;
            nzones = pmNZones.Value;
            ZoneOwner.Clear();
            ZoneOwners.Clear();
            ZoneStatus.Clear();
            ZonesOwned.Clear();
            ZoneTaking.Clear();
            ShipsOwned.Clear();
            countdown = 60;
            CCcount = 200;
            List<SCGPoint> ZoneLocation = new List<SCGPoint>();
            List<SCGPoint> BHLocation = new List<SCGPoint>();
            StarShip freight = null;
            int totalzones = nzones + totalplayers;
            int x = Random(20, 80);
            int y = Random(20, 80);
            for (int d = 0; d < totalzones; d++)
            {
                if (d < totalplayers)
                {
                    ZoneOwner.Add(Game.Players[d]);
                    ZoneStatus.Add(-15);
                    ZonesOwned.Add(Game.Players[d], 1);
                    ZoneConflict.Add(false);
                    ZoneTaking.Add(false);
                    ZoneOwners.Add(1);
                }
                else
                {
                    ZoneOwner.Add(null);
                    ZoneStatus.Add(0);
                    ZoneConflict.Add(false);
                    ZoneTaking.Add(false);
                    ZoneOwners.Add(0);
                }
                x = Random(20, 80);
                y = Random(20, 80);
                if (d == 0)
                {
                    UDO udo = CreateUDO("SpacePort", "SpacePort", x, y);
                    udo.AutoPickUp = false;
                    udo.IsTaggable = false;
                    udo.IgnoreBlackHoles = true;
                    udo.Description = "Hold this port for 15 impulses to own it and hold it for 30 to take it over from an opponent. " +
                                      "If more than one player has a starship within the zone, the takeover will freeze until only one player is within the zone.";
                    ZoneLocation.Add(new SCGPoint(x,y));
                    if (d < totalplayers)
                    {
                        freight = CreateStarShip(x - 1, y - 1, Game.Players[d], StarShipType.BattleStation, 6, 100, true);
                        BattleStation bs = freight as BattleStation;
                        bs.Resources = (double)startingResources;  
                        CreateStarShip(x, y, Game.Players[d], StarShipType.ScanShip, 20, 20, false);
                    }
                }
                else
                {
                    bool locationok = false;
                    while (locationok == false)
                    {
                        x = Random(20, 80);
                        y = Random(20, 80);
                        locationok = true;
                        for (int s = 0; s < ZoneLocation.Count; s++)
                        {
                            if (DistanceQuick(ZoneLocation[s].X, ZoneLocation[s].Y, x, y) <= 12) locationok = false;
                        }
                    }
                    UDO udo = CreateUDO("Port", "SpacePort", x, y);
                    udo.AutoPickUp = false;
                    udo.IsTaggable = false;
                    udo.Tag = d;
                    udo.IgnoreBlackHoles = true;
                    udo.Description = "Hold this port for 15 impulses to own it and hold it for 30 to take it over from an opponent. " +
                                      "If more than one player has a starship within the zone, the takeover will freeze until only one player is within the zone.";
                    ZoneLocation.Add(new SCGPoint(x, y));
                    if (d < totalplayers)
                    {
                        freight = CreateStarShip(x - 1, y - 1, Game.Players[d], StarShipType.BattleStation, 6, 100, true);
                        BattleStation bs = freight as BattleStation;
                        bs.Resources = (double)startingResources;  
                        CreateStarShip(x, y, Game.Players[d], StarShipType.ScanShip, 20, 20, false);
                    }
                }
            }

            int numobj = Random(1, 2);
            if (pmNebula.Value == 1)
            {
                for (int d = 0; d < numobj; d++)
                {
                    x = Random(10, 89);
                    y = Random(10, 89);
                    CreateTerrain(TerrainType.Nebula, x, y, Random(1, 2), Random(2500, 5000));
                }
            }
            numobj = Random(3, 10);
            if (pmWormHoles.Value == 1)
            {
                for (int d = 0; d < numobj; d++)
                {
                    x = Random(20, 79);
                    y = Random(20, 79);
                    CreateWormhole(x, y, Random(2, 97), Random(2, 97));
                }
            }
            numobj = Random(3, 12);
            if (pmBlackHoles.Value == 1)
            {
                for (int d = 0; d < numobj; d++)
                {
                    bool placeok = false;
                    while (placeok == false)
                    {
                        placeok = true;
                        x = Random(0, 99);
                        y = Random(0, 99);
                        if (Distance(x, y, 49, 49) >= 45)
                        {
                            for (int s = 0; s < BHLocation.Count; s++)
                            {
                                if (Distance(x, y, BHLocation[s].X, BHLocation[s].Y) < 12)
                                    placeok = false;
                            }
                        }
                        else
                        {
                            placeok = false;
                        }
                    }
                    if (placeok == true)
                    {
                        CreateBlackHole(x, y, Random(8, 14));
                        BHLocation.Add(new SCGPoint(x, y));
                    }
                }
            }
            numobj = Random(2, 5);
            if (pmPulsars.Value == 1)
            {
                for (int d = 0; d < numobj; d++)
                {
                    x = Random(15, 84);
                    y = Random(15, 84);
                    CreatePulsar(x, y);
                }
            }
            if (pmMode.Value == 3)
            {
                StarSystem sys = CreateStarSystem(Random(45, 55), Random(45, 55), 0, 100, 0, 0);
                sys.Name = "Central Control";
            }

            TransmitData();
            sceninit = true;
            SetValue("initdone", sceninit.ToString());
        }

        private void TransmitData()
        {
            foreach (Player ply in Game.Players)
            {
                if (ply.Victor == true)
                {
                    foreach (Player ply2 in Game.Players)
                    {
                        if ((ply != ply2) & (ply2.Victor == false))
                            ply2.Eliminated = true;
                    }
                }
                SetValue("ZOwned" + ply.Name, ZonesOwned[ply].ToString());
            }
            for (int d = 0; d < Game.UDOs.Count; d++)
            {
                SetValue("ZOwners" + d.ToString(), ZoneOwners[d].ToString());
                SetValue("ZConflict" + d.ToString(), ZoneConflict[d].ToString());
                if (ZoneOwner[d] != null)
                    SetValue("ZOwner" + d.ToString(), ZoneOwner[d].Name);
                else
                    SetValue("ZOwner" + d.ToString(), "");
                SetValue("ZTaking" + d.ToString(), ZoneTaking[d].ToString());
                SetValue("ZStat" + d.ToString(), ZoneStatus[d].ToString());
            }
            SetValue("countdown", countdown.ToString());
            SetValue("CCcount", CCcount.ToString());
            SetValue("GameMode", pmMode.Value.ToString());
        }

        //render custom visuals
        public override void CustomRendering(ISVCustomRenderer renderer)
        {
            renderer.DrawTextScreenCoords(_s1, 8, 8, _s1Color, 12);
            renderer.DrawTextScreenCoords(_s2, 8, 28, _s2Color, 12);
            renderer.DrawTextScreenCoords(_countdown, 8, 48, _countdownColor, 14);

            //render zones
            int idx = 0;
            foreach (UDO udo in Game.UDOs)
            {
                //is the zone visible?
                if (udo.VisibleToCurrentPlayer)
                {
                    //set the color based on owner
                    SCGColor zoneColor = _ZonePen;
                    Player owner = ZoneOwner[idx];
                    if (owner != null)
                        zoneColor = owner.Color;

                    //Is it in conflict?
                    SCGColor zoneFill = SCGColor.Transparent;
                    if (ZoneTaking[idx])
                        zoneFill = _ZoneTaking;
                    else if (ZoneConflict[idx])
                        zoneFill = _ZoneConflict;

                    renderer.FillRectangle(udo.X - 3, udo.Y - 3, udo.X + 3, udo.Y + 3, zoneColor, zoneFill, 3);

                    //glyph for zone owner
                    if (owner != null)
                        renderer.DrawImage(owner.Glyph, udo.X - 3, udo.Y - 3, 2, 2);

                    //status for zone   
                    double status = ZoneStatus[idx];
                    if (status > 0)
                    {
                        string statusMark = "";
                        int num = (int)(16 - status);
                        while (num > 0)
                        {
                            statusMark += "*";
                            num--;
                        }
                        renderer.DrawText(statusMark, udo.X - 3, udo.Y - 2, 0, 0, SCGColor.Silver, 12);
                    }
                }
                idx++;
            }
        }

        //Process the Visuals
        private string _s1 = "";
        private SCGColor _s1Color = SCGColor.Red;
        private string _s2 = "";
        private SCGColor _s2Color = SCGColor.Red;
        private string _countdown = "";
        private SCGColor _countdownColor = SCGColor.Red;
        public override void ClientProcessImpulse(int impulse)
        {
            string s;
            s = GetValue("initdone");
            if (s == "")
                s = "true";

            sceninit = Boolean.Parse(s);
            if (sceninit == false)
            {
                s = GetValue("countdown");
                if (s == "")
                    s = "50";
                countdown = Int32.Parse(s);
                s = GetValue("GameMode");
                if (s == "")
                    s = "1";
                pmMode.Value = Int32.Parse(s);
                s = GetValue("CCcount");
                if (s == "")
                    s = "200";
                CCcount = Int32.Parse(s);
                foreach (StarShip ship in Game.StarShips)
                {
                    if (ship.ShipType == StarShipType.BattleStation)
                    {
                        BattleStation bs = ship as BattleStation;
                        s = GetValue("BST" + ship.Code);
                        if (s != "") bs.Resources = Single.Parse(s);
                    }
                }
                foreach (Player ply in Game.Players)
                {
                    s = GetValue("ZOwned" + ply.Name);
                    if (s == "")
                        s = "0";
                    if (ZonesOwned.ContainsKey(ply) == false)
                    {
                        ZonesOwned.Add(ply, Int32.Parse(s));
                    }
                    else
                    {
                        ZonesOwned[ply] = Int32.Parse(s);
                    }
                }

                //Draw the zones
                for (int d = 0; d < Game.UDOs.Count; d++)
                {
                    s = GetValue("ZOwners" + d.ToString());
                    if (s == "")
                        s = "0";
                    if (ZoneOwners.Count < Game.UDOs.Count)
                    {
                        ZoneOwners.Add(Int32.Parse(s));
                    }
                    else
                    {
                        ZoneOwners[d] = Int32.Parse(s);
                    }
                    s = GetValue("ZConflict" + d.ToString());
                    if (s == "")
                        s = "False";
                    if (ZoneConflict.Count < Game.UDOs.Count)
                    {
                        ZoneConflict.Add(Boolean.Parse(s));
                    }
                    else
                    {
                        ZoneConflict[d] = Boolean.Parse(s);
                    }
                    s = GetValue("ZOwner" + d.ToString());
                    if (s != "")
                    {
                        Player tmpp = FindPlayerWithName(s);
                        if (tmpp != null)
                        {
                            if (ZoneOwner.Count < Game.UDOs.Count)
                            {
                                ZoneOwner.Add(tmpp);
                            }
                            else
                            {
                                ZoneOwner[d] = tmpp;
                            }
                        }
                    }
                    else
                    {
                        if (ZoneOwner.Count < Game.UDOs.Count)
                        {
                            ZoneOwner.Add(null);
                        }
                        else
                        {
                            ZoneOwner[d] = null;
                        }
                    }
                    s = GetValue("ZTaking" + d.ToString());
                    if (s == "")
                        s = "False";
                    if (ZoneTaking.Count < Game.UDOs.Count)
                    {
                        ZoneTaking.Add(Boolean.Parse(s));
                    }
                    else
                    {
                        ZoneTaking[d] = Boolean.Parse(s);
                    }
                    s = GetValue("ZStat" + d.ToString());
                    if (s == "")
                        s = "0";
                    if (ZoneStatus.Count < Game.UDOs.Count)
                    {
                        ZoneStatus.Add(Int32.Parse(s));
                    }
                    else
                    {
                        ZoneStatus[d] = Int32.Parse(s);
                    }
                }

                int TeamZones = ZonesOwned[Game.CurrentPlayer];
                for (int d = 0; d < Game.UDOs.Count; d++)
                {
                    if (ZoneOwner[d] != null)
                    {
                        if ((Game.CurrentPlayer.AlliedWith(ZoneOwner[d]) == AllianceLevel.Formal) & (ZoneOwner[d].AlliedWith(Game.CurrentPlayer) == AllianceLevel.Formal))
                        {
                            TeamZones++;
                        }
                    }
                }

                if (TeamZones > ZonesOwned[Game.CurrentPlayer])
                {
                    s = "SpacePorts your team owns: " + TeamZones + " of " + Game.UDOs.Count.ToString();
                }
                else
                {
                    s = "SpacePorts you own: " + TeamZones + " of " + Game.UDOs.Count.ToString();
                }

                _s1 = s;
                _s1Color = SCGColor.Red;

                if (pmMode.Value == 3)
                {
                    StarSystem CentralControl = Game.StarSystems[0]; //only one starsystem in this mode
                    if (CentralControl.Owner != null)
                    {
                        if ((CentralControl.Owner.Name == Game.CurrentPlayer.Name) |
                            (Game.CurrentPlayer.AlliedWith(CentralControl.Owner) == AllianceLevel.Formal))
                        {
                            s = "Countdown to Victory: " + CCcount.ToString();
                            _s2 = s;
                            _s2Color = SCGColor.Green;
                        }
                        else
                        {
                            s = "Countdown to Defeat: " + CCcount.ToString();
                            _s2 = s;
                            _s2Color = SCGColor.Red;
                        }
                    }
                }

                if (countdown < 60)
                {
                    if ((ZonesOwned[Game.CurrentPlayer] >= Game.UDOs.Count) | (TeamZones >= Game.UDOs.Count))
                    {
                        s = "Impulses left to victory: " + countdown.ToString();
                        _countdown = s;
                        _countdownColor = SCGColor.Green;
                    }
                    else
                    {
                        s = "Impulses left to defeat: " + countdown.ToString();
                        _countdown = s;
                        _countdownColor = SCGColor.Red;
                    }
                }
                else
                    _countdown = "";
            }
        }

        //Dynamic processing
        public override void ProcessImpulse(int impulse)
        {
            string tmpstr = "Players and Starships";
            try
            {
                int totalzones = pmNZones.Value + Game.Players.Count;
                BstValue = 20;

                foreach (Player ply in Game.Players)
                {
                    if (ShipsOwned.ContainsKey(ply.Name) == false)
                        ShipsOwned.Add(ply.Name, 0);
                    else
                        ShipsOwned[ply.Name] = 0;
                }
                foreach (StarShip ship in Game.StarShips)
                {
                    ShipsOwned[ship.Owner.Name]++;
                    if (ship.ShipType == StarShipType.BattleStation)
                    {
                        //Generate resources on every battlestation in play.
                        BstValue = ship.Value;
                        BattleStation bs = ship as BattleStation;
                        bs.Resources = bs.Resources + (((double)BstValue / 200.0) * ship.Owner.TechMultiple);
                        SetValue("BST" + ship.Code, bs.Resources.ToString()); //transmit resources of BattleStations to each player
                    }
                }
                if (pmMode.Value == 3)
                {
                    StarSystem CentralControl = Game.StarSystems[0]; //only one starsystem in this mode
                    if (CentralControl.Owner != null)
                    {
                        if (laststarowner != CentralControl.Owner.Name)
                        {
                            laststarowner = CentralControl.Owner.Name;
                            CCcount = 200;
                        }
                        else
                        {
                            if (CCcount <= 0)
                            {
                                DeclareCountdownWinners(CentralControl.Owner.Name);
                            }
                            else
                            {
                                CCcount--;
                            }
                        }
                    }
                    else
                    {
                        CCcount = 200;
                    }
                }

                //check to see if there are starships within a zone
                tmpstr = "UDOS 1";
                for (int d = 0; d < Game.UDOs.Count; d++)
                {
                    if (ZoneOwners.Count < Game.UDOs.Count)
                        ZoneOwners.Add(0);
                    ZoneOwners[d] = 0;
                    Player lastowner = null;
                    UDO obj = Game.UDOs[d];
                    foreach (StarShip ship in Game.StarShips)
                    {
                        if (IsStarshipWithinZone(ship, new SCGRect(obj.X - 3, obj.Y - 3, 6, 6)))
                        {
                            if (lastowner == null)
                            {
                                ZoneOwners[d]++;
                                lastowner = ship.Owner;
                            }
                            else if (ship.Owner != lastowner)
                            {
                                if (ZoneOwner[d] != null)
                                {
                                    if (((ship.Owner.AlliedWith(lastowner) == AllianceLevel.None) | (lastowner.AlliedWith(ship.Owner) == AllianceLevel.None)) & 
                                        (ship.Owner.AlliedWith(ZoneOwner[d]) == AllianceLevel.None))  //filter out allied starships on a unowned zone
                                    {
                                        ZoneOwners[d]++;
                                        lastowner = ship.Owner;
                                    }
                                }
                                else
                                {
                                    if ((ship.Owner.AlliedWith(lastowner) == AllianceLevel.None) | (lastowner.AlliedWith(ship.Owner) == AllianceLevel.None)) //filter out allied starships on a unowned zone
                                    {
                                        ZoneOwners[d]++;
                                        lastowner = ship.Owner;
                                    }
                                }
                            }
                        }
                    }
                }
                //0 = no starship within the zone, 1 = only one player has the zone, >1 more than one player has the zone
                tmpstr = "UDOS 2";
                for (int d = 0; d < Game.UDOs.Count; d++)
                {
                    UDO obj = Game.UDOs[d];
                    if (ZoneOwners[d] != 1)
                    {
                        if (ZoneOwner[d] == null)
                        {
                            ZoneStatus[d] = 0;
                        }
                        else
                        {
                            ZoneStatus[d] = -15;
                        }
                        if (ZoneOwners[d] > 1)
                        {
                            ZoneConflict[d] = true;
                            ZoneTaking[d] = false;
                        }
                        else
                        {
                            ZoneTaking[d] = false;
                            ZoneConflict[d] = false;
                        }
                    }
                    else
                    {
                        ZoneConflict[d] = false;
                        Player lastowner = null;
                        foreach (StarShip ship in Game.StarShips)
                            if (IsStarshipWithinZone(ship, new SCGRect(obj.X - 3, obj.Y - 3, 6, 6)))
                                lastowner = ship.Owner;

                        if (ZoneOwner[d] == null)
                        {
                            if (ZoneStatus[d] >= 15)
                            {
                                ZoneOwner[d] = lastowner;
                                ZoneStatus[d] = -16;
                                ZoneTaking[d] = false;
                                ZonesOwned[lastowner]++;
                            }
                            else
                            {
                                ZoneTaking[d] = true;
                            }
                            ZoneStatus[d]++;
                        }
                        else
                        {
                            if ((ZoneOwner[d] != lastowner) & ((ZoneOwner[d].AlliedWith(lastowner) == AllianceLevel.None) | (lastowner.AlliedWith(ZoneOwner[d]) == AllianceLevel.None)))
                            {
                                if (ZoneStatus[d] >= 0)
                                {
                                    ZonesOwned[ZoneOwner[d]]--;
                                    ZoneOwner[d] = null;
                                    ZoneStatus[d] = -1;
                                    ZoneTaking[d] = false;
                                }
                                else
                                {
                                    ZoneTaking[d] = true;
                                }
                                ZoneStatus[d]++;
                            }
                        }
                    }
                }
                tmpstr = "Players 1";
                Dictionary<string, int> TTLZones = new Dictionary<string, int>();
                List<int> CZones = new List<int>();
                int adx = 0;
                //Generate an alliance zone owner matrix
                foreach (Player ply in Game.Players)
                {
                    CZones.Add(ZonesOwned[ply]);
                    if (!ply.Eliminated)
                    {
                        foreach (Player ply2 in Game.Players)
                        {
                            if ((!ply.Eliminated) & (ply.Name != ply2.Name))
                            {
                                if ((ply.AlliedWith(ply2) == AllianceLevel.Formal) &
                                    (ply2.AlliedWith(ply) == AllianceLevel.Formal))
                                {
                                    CZones[adx] = CZones[adx] + ZonesOwned[ply2];
                                }
                            }
                        }
                    }
                    adx++;
                }
                adx = 0;
                //string scoreboard = "";
                foreach (Player ply in Game.Players)
                {
                    if (TTLZones.ContainsKey(ply.Name) == false)
                        TTLZones.Add(ply.Name, CZones[adx]);
                    //scoreboard = scoreboard + "," + TTLZones[ply.Name];
                    adx++;
                }
                adx = 0;

                //DynamicEvents.DisplayMessage(scoreboard);

                tmpstr = "Players 2";
                bool counted = false;
                foreach (Player ply in Game.Players)
                {
                    if (!ply.Eliminated)
                    {
                        if (((ZonesOwned[ply] >= Game.UDOs.Count) | (TTLZones[ply.Name] >= Game.UDOs.Count)) & (counted == false))
                        {
                            countdown--;
                            if (countdown <= 0)
                            {
                                DeclareCountdownWinners(ply.Name);
                            }
                            counted = true;
                        }
                        else if ((ZonesOwned[ply] > 0) & (TTLZones[ply.Name] < Game.UDOs.Count))
                        {
                            countdown = 60;
                        }
                        if (ShipsOwned[ply.Name] <= 0)
                            ply.Eliminated = true;
                        if (ShipsOwned[ply.Name] >= Game.StarShips.Count)
                            ply.Victor = true;
                        StarShipAllianceWinCheck(ply);
                    }
                }
                tmpstr = "Set Values";
                TransmitData();
                sceninit = false;
                SetValue("initdone", sceninit.ToString());
            }
            catch (Exception ex)
            {
                DynamicEvents.DisplayMessage("Process Impulse Error at " + tmpstr + " " + ex.Message);
            }
        }

        private bool IsStarshipWithinZone(StarShip sh, SCGRect rs)
        {
            bool bval = ((sh.X >= rs.X) & (sh.Y >= rs.Y) & (sh.X <= rs.Right) & (sh.Y <= rs.Bottom));
            return bval;
        }

        private Player FindPlayerWithName(string pName)
        {
            Player tmpplay = null;
            foreach (Player pl in Game.Players)
            {
                if (pl.Name == pName) tmpplay = pl;
            }
            return tmpplay;
        }


    }
}
